const JWT = require('../utils/jwt.js');
const { executeQuery } = require('../utils/dataAccess');

// 登录
exports.login = async (req, res, next) => {
    try {
        let {username, password} = (req.body);
        if(!username || !password) throw new Error('用户名或密码不能为空');

        let sqlStatement = `SELECT * FROM sys_user WHERE user_name = '${username}' AND password = '${password}';`;

        const data = await executeQuery(sqlStatement);
        if(data.rows.length === 0) throw new Error('用户名或密码错误');

        res.json({
            code: 200,
            mwssage: '登录成功',
            token: JWT.createToken({ ...data.rows[0] }, '36000s'),
        });
    } catch (error) {
        next(error);
    }
}

// 获取用户信息
exports.getInfo = async (req, res, next) => {
    try {

        let user_id = req.auth.user_id;
        let role_id = [];
        let roles_menu = [];
        let permissions = []


        async function getRoles(){
            let sql = `SELECT role_id FROM sys_user_role WHERE user_id = '${user_id}';`;
            try {  
                const result = await executeQuery(sql);
                let roles = result.rows
                role_id = roles.map(role => role.role_id);  // 获取角色id数组
            } catch (err) {  
                next(err); // 如果发生错误，抛出异常  
            } 
        }

        async function getMenuIds(){
            let sql = `SELECT * FROM sys_role_menu where role_id = '${role_id[0]}'`;
            try {
                const result = await executeQuery(sql);  // 获取角色菜单权限信息
                menuids = result.rows;  // 获取角色菜单权限信息数组

                menuids.forEach(element => {
                    roles_menu.push(element.menu_id);  // 获取角色菜单权限信息数组
                });
                
            } catch (err) {
                next(err);  // 如果发生错误，抛出异常
            }
        }

        async function getPermissions(){
            let sql = `SELECT * FROM sys_menu WHERE menu_id IN ('${roles_menu.join("','")}')`;  // 获取角色菜单权限信息数组
            try {  
                const result = await executeQuery(sql);  // 获取角色菜单权限信息数组  
                // permissions = result.recordsets[0];  // 获取角色菜单权限信息数组
                let menuList = result.rows
                if(menuList.length > 0){
                    menuList.forEach(item=>{
                        if(item.perms != 'null' && item.perms != ''){
                            permissions.push(item.perms);  // 获取角色菜单权限信息数组
                        }
                    })
                }else{
                    permissions = [];  // 获取角色菜单权限信息数组
                }
            } catch (err){
                next(err);  // 如果发生错误，抛出异常
            }
        }

        await getRoles();

        if(req.auth.user_name == 'admin'){
            permissions = ['*:*:*'];
        }else{
            await getMenuIds();
            await getPermissions();
        }
        let userInfo = {
            admin: req.auth.user_name == 'admin' ? true : false,
            avatar: req.auth.avatar,
            createBy: req.auth.create_by,
            createTime: req.auth.create_time,
            delFlag: req.auth.del_flag,
            dept:[],
            deptId: req.auth.dept_id,
            email: req.auth.email,
            loginDate: req.auth.login_date,
            loginIp: req.auth.login_ip,
            nickName: req.auth.nick_name,
            password: req.auth.password,
            phonenumber: req.auth.phonenumber,
            postIds: [],
            remark: req.auth.remark,
            roleId: '',
            roleIds: [],
            roles: [],
            sex: req.auth.sex,
            status: req.auth.status,
            updateBy: req.auth.update_by,
            updateTime: req.auth.update_time,
            userId: req.auth.user_id,
            userName: req.auth.user_name,
        }

    
        res.json({
            code: 200,
            message: '请求成功',
            permissions: permissions,
            roles: role_id,
            user: userInfo
        })
    }
    catch (err) {
        res.status(500).send(err.message); // 返回错误信息
    }
}


// 退出登录
exports.logout = (req, res) => {
    res.json({ code: 200, message: '退出成功'})
}